//
//  Proxy.m
//  Staff
//
//  Created by caiyao on 1/13/15.
//
//

#import "Proxy.h"
#import "Reachability.h"
#import "NSString+SBJSON.h"

@implementation Proxy

- (void)dealloc {
    
    [super dealloc];
}

- (void)excute {
 
    if (([self.command.functionParamsDic objectForKey:@"url"]  == nil)||(self.command.callbackJS == nil))
    {
        // params is missing fail to handle
        [self excuteNonHookFoundCallback];
        return;
    }
    
    NSString *urlToOpen = [[self.command.functionParamsDic objectForKey:@"url"] stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
    
    if (![urlToOpen hasPrefix:@"http"])
    {
        urlToOpen = [NSString stringWithFormat:@"%@%@",@"https://",urlToOpen];
    }
    DebugLog(@"opening URL %@ in new modal view: ",urlToOpen);
    
    NSString *jsResponse = nil;
    
    NSString *datajsFunc = self.command.dataJS;
    if (datajsFunc != nil)
    {
        NSString *jsCall = [NSString stringWithFormat:@"%@();",datajsFunc];
        
        jsResponse = [self.webView stringByEvaluatingJavaScriptFromString:jsCall];
        
        DebugLog(@"jsResponse:%@",jsResponse);
    }
    
    NSString *method = [self.command.functionParamsDic objectForKey:@"method"];
    
    // network can not be reachable error code 'P004'    
    BOOL isConnect = [Reachability checkNetWorkConnective];
    if (isConnect == NO)
    {
        [self excuteCallBackJSWithParameters:([NSString stringWithFormat:@"{\"header\":{\"statusCode\": \"%@\" }}", region_webview_status_code_p004])];
        return;
    }
    
    NSTimeInterval timeout = http_con_default_timeout;
    ChaosRequest *request = [[ChaosRequest alloc] init];
    request.connectionURLString = urlToOpen;
    request.connectionBody = jsResponse;
    request.httpMethod = method;
    request.timeout = timeout;
    request.isHSBCProxy = YES;
    request.delegate = self;
    [[ChaosAgent sharedAgent] inqueue:request];

    
    return;
}

- (void)response:(ChaosResponse *)resp {
    if (resp.httpStatusCode == 200) {
        
        NSString *returnString = [[NSString alloc] initWithData:resp.responseData encoding:NSUTF8StringEncoding];
        DebugLog(@"returnString is %@",returnString);
        
        BOOL isJSON = YES;
        
        NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
        DebugLog(@"start try to paser the string as json object.");
        NSDictionary *proxyInfo= [returnString JSONValue];
        DebugLog(@"end try to paser the string as json object.");
        if (proxyInfo != nil)
        {
            isJSON =YES;
        }
        [pool release];
        
        NSString *jsChange= returnString;
        
        if (isJSON == YES)
        {
            // proxy recevie is a json object
            jsChange= [jsChange stringByReplacingOccurrencesOfString:@"\r" withString:@""];
            jsChange= [jsChange stringByReplacingOccurrencesOfString:@"\n" withString:@""];
            
            jsChange= [jsChange stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"];
            jsChange= [jsChange stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
        }
        else
        {
            // proxy recevie is a string
            jsChange= [jsChange stringByReplacingOccurrencesOfString:@"\r" withString:@""];
            jsChange= [jsChange stringByReplacingOccurrencesOfString:@"\n" withString:@""];
            
            jsChange = [jsChange stringByReplacingOccurrencesOfString:@"\\\"" withString:@"\""];
            jsChange = [jsChange stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
        }
        
        if (jsChange == nil)
        {
            
            [self excuteCallBackJSWithParameters:([NSString stringWithFormat:@"{\"header\":{\"statusCode\": \"%@\" }}", region_webview_status_code_p002])];
            [returnString release];
            return;
        }
        [self excuteCallBackJSWithParameters:jsChange];
        [returnString release];
    
    }else {
        if (resp.httpStatusCode == -1001) {
            [self excuteCallBackJSWithParameters:([NSString stringWithFormat:@"{\"header\":{\"statusCode\": \"%@\" }}", error_code_p001])];
        } else {
            [self excuteCallBackJSWithParameters:([NSString stringWithFormat:@"{\"header\":{\"statusCode\": \"%@\" }}", error_code_p002])];
        }
    }
}

@end
